package com.ccg.plat.presentation.ui.feature1.viewmodel

import android.app.Activity
import android.app.Application
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.FileIOUtils
import com.blankj.utilcode.util.PathUtils
import com.ccg.plat.data.local.cache.UserInfoCache
import com.ccg.plat.presentation.common.base.viewmodel.BaseViewModelC
import com.ccg.plat.presentation.common.util.NavigationUtils
import com.ccg.plat.presentation.ui.feature1.model.UpdateBean
import com.google.gson.GsonBuilder
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.consumeAsFlow
import timber.log.Timber

/**
 * @author : C4_雍和
 * 描述 :
 * 主要功能 :
 * 维护人员 : C4_雍和
 * date : 2025/8/9 7:55
 */
class WelcomeViewModel(application: Application) : BaseViewModelC(application) {
    /**
     * 定义意图
     */
    sealed class ContentIntent {
        /**
         * 获取页面数据
         * @property activity Activity
         * @constructor
         */
        class GetLatestVersion(val activity: Activity) : ContentIntent()
    }

    /**
     * UI状态
     * @property tagStr String
     * @constructor
     */
    data class NaviViewState(var tagStr: String = "")

    val newsChannel = Channel<ContentIntent>(Channel.UNLIMITED)
    var uiState by mutableStateOf(NaviViewState())

    init {
        handleIntent()
    }

    private fun handleIntent() {
        launch(Dispatchers.IO) {
            newsChannel.consumeAsFlow().collect { data ->
                when (data) {
                    is ContentIntent.GetLatestVersion -> {
                        getLatestVersion(data.activity)
                    }

                }
            }
        }
    }

    /**
     * 获取最新版本
     * @param activity Activity
     */
    private suspend fun getLatestVersion(activity: Activity) {
        val mJson = "http://117.72.114.24:8083/xiaohuanger"
        //获取用户信息
        if (UserInfoCache.getBaseUrl().isEmpty()) {
            UserInfoCache.setBaseUrl(mJson)
        }
        uiState = uiState.copy(tagStr = "获取最新版本")
        var updateJson = MMKV.defaultMMKV().decodeString("update", "")
        if (updateJson.isNullOrEmpty()) {
            //如果没有缓存请求服务器获取最新版本
            updateJson = retrofit.getNetData("${UserInfoCache.getBaseUrl()}/update.json").string()
            MMKV.defaultMMKV().encode("update", updateJson, MMKV.ExpireInDay)
        }
        //请求获取最新版本
        val updataInfoData = GsonBuilder().create().fromJson(updateJson, UpdateBean::class.java)
        if (updataInfoData.version > AppUtils.getAppVersionCode()) {
            //如果有最新版本下载安装
            val destPath = PathUtils.getInternalAppFilesPath() + "/xhr.apk"
            uiState = uiState.copy(tagStr = "下载最新版本")
            val inputStream = retrofit.getNetData(updataInfoData.apkUrl).byteStream()
            val isSuccessful = FileIOUtils.writeFileFromIS(destPath, inputStream)
            uiState = uiState.copy(tagStr = "下载最新版本" + isSuccessful)
            if (isSuccessful) {
                uiState.tagStr = "安装app中"
                delay(1000L)
                AppUtils.installApp(destPath)
            }
        } else {
            NavigationUtils.goMainActivity(activity)
        }
    }
}